<template>
  <div>
    <c-model v-model="show" title="设备详情" width="700px" customClass="device-model">
      <div slot="title" class="head-title"><span class="iconfont icon-order"/>设备详情</div>
      <div class="device-info" v-if="device">
        <div class="img-box">
          <Carousel ref="carousel" v-model="currImgIndex" class="img-list" :height="260" loop dots="none" arrow="always">
            <CarouselItem v-for="(item, index) in imgList" :key="index">
              <img :src="item" alt=""/>
            </CarouselItem>
          </Carousel>
        </div>
        <div class="info">
          <div class="name"><span class="label">原价{{device.cashMoney}}</span>{{ device.equipmentName }}</div>
          <div class="desc color-muted mb-5">剩余库存{{ device.stock }}</div>
          <div class="cell-group" style="border-top: 1px solid #E6E6E6">
            <div class="cell col-top">
              <div class="label">租赁方式</div>
              <div class="con money-list">
                <div class="money-item"
                     :class="{active: moneyIndex == index}"
                     v-for="(item, index) in device.moneyList"
                     :key="index"
                     @click="moneyIndex = index"
                >
                  <div class="one">
                    <div class="bold">{{item.hours}}小时</div>
                    <div class="line-price text-line" v-if="item.disPrice && item.disPrice > item.price">￥<span>{{item.disPrice}}</span></div>
                  </div>
                  <div class="two">￥<span>{{item.price}}</span></div>
                </div>
              </div>
            </div>
            <div class="cell">
              <div class="label">优惠金额</div>
              <div class="con"><div class="price color-orange">￥<span>{{ currMoney.disPrice }}</span></div></div>
            </div>
            <div class="cell">
              <div class="label">总计</div>
              <div class="con"><div class="price color-brown">￥<span>{{ currMoney.price }}</span></div></div>
            </div>
            <div class="cell col-base">
              <div class="label">支付方式</div>
              <div class="con pay-type">
                <button class="pay-item free-item area mt-8"
                        v-if="device.areaName"
                        :disabled="device.isFree != 2"
                        :class="{active: payType == -2}" @click="payType = -2">
                  <div class="free line-clamp">{{device.areaName}}</div>
                  <span class="iconfont icon-computer mr-4"/>终端免费
                </button>
                <template v-if="device.isFree != 2">
                  <button class="pay-item" :class="{active: payType == 5}" @click="payType = 5">
                    <span class="iconfont icon-wechat mr-4"/>微信
                  </button>
                  <button class="pay-item" :class="{active: payType == 6}" @click="payType = 6">
                    <span class="iconfont icon-ali mr-4"/>支付宝
                  </button>
                </template>
              </div>
            </div>
          </div>
          <div class="flex col-center row-between mt-20">
            <div class="agree-box fz-12 color-muted">
              <div class="agree-tip" v-if="agreeTipShow">请勾选协议</div>
              <div class="agree-box-item flex col-center cursor" @click="changeAgreement">
                <img :src="isAgreement ? checkedIcon: checkIcon" class="mr-5" alt=""/>
                <span>已阅读并同意<span class="cursor color-brown" @click.stop="agreementShow = true">《电竞蜂用户租赁服务协议》</span></span>
              </div>
            </div>
            <i-button type="primary" :loading="submitLoading" @click="createOrder" v-if="device.stock">提交租赁</i-button>
            <i-button disabled type="info" v-else>已抢光</i-button>
          </div>
        </div>
      </div>
      <div class="sku-box" v-if="device">
        <div class="sku-label">设备参数</div>
        <div class="sku-table">
          <table>
            <tr v-for="(item, index) in paramsList" :key="index">
              <td class="label">{{ item.name }}</td>
              <td class="con">{{item.value}}</td>
            </tr>
          </table>
        </div>
      </div>
      <div slot="footer"></div>
    </c-model>
    <agreement v-model="agreementShow"
      :device="device"
      :currMoney="currMoney"
      @close="agreementShow = false"
    />
    <scan-pay v-model="payModel.show"
              :money="currMoney.price"
              :payType="payModel.payType"
              :orderType="3"
              :qrcode="payModel.qrcode"
              :orderNumber="payModel.orderNumber"
              @fail="payFail"
              @success="paySuccess"/>
    <c-model v-model="payModel.finishShow" title="支付提示" width="400px" custom-class="pay-tooltip">
      <div class="content tc">
        <div class="status-img iconfont icon-success"></div>
        <div class="fz-18 bold">下单成功</div>
        <div class="fz-16 mb-40 mt-8">请等待店员配送设备</div>
        <div class="mb-20">
          <i-button type="primary" class="w-96" @click="payModel.finishShow = false">确定</i-button>
        </div>
      </div>
      <div slot="footer"></div>
    </c-model>
  </div>
</template>
<script>
import Agreement from "./agreement.vue";
import ScanPay from "@/components/scanPay/index.vue";
import {mapGetters} from "vuex";
import {createLeaseOrder, deviceDetail, leaseOrderPay} from "@/api/deviceLease";
import {encryptByDESModeCBCUtf8to64} from "@/common/utils/des";
import {getRule} from "@/api/common";
export default {
  name: "detail",
  components: {Agreement, ScanPay},
  props: {
    value: {type: Boolean, default: false},
    deviceId: {type: Number|String, default: null},
  },
  data() {
    return {
      device: null,
      currImgIndex: 0,
      agreementShow: false,
      isAgreement: false,
      agreeTipShow: false,
      moneyIndex: 0,
      payType: 5,
      submitLoading: false,
      payModel: {
        show: false,
        finishShow: false
      }
    }
  },
  computed: {
    show: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      }
    },
    imgList() {
      if (!this.device) return []
      if (!this.device.imgList) {
        return [this.device.logo]
      }
      return this.device.imgList.split(',')
    },
    moneyList() {
      if (this.device) {
        return this.device.moneyList
      }
      return []
    },
    currMoney() {
      const item = this.moneyList[this.moneyIndex]
      if (!item) {
        return {
          otPrice: 0,
          price: 0,
          hours: 0,
          disPrice: 0
        }
      }
      let price = this.payType < 0 ? 0 :item.price
      return {
        otPrice: item.price,
        price: price,
        disPrice: !price ? item.price: 0,
        hours: item.hours
      }
    },
    paramsList() {
      return this.device ? JSON.parse(this.device.paramJson) : []
    }
  },
  methods: {
    init() {
      this.submitLoading = false
      this.isAgreement = false
      this.payType = 5;
      deviceDetail({equipmentId: this.deviceId}).then(res => {
        if (res.code != 200) {
          this.$Message.error(res.msg || '获取设备详情失败')
          return
        }
        let data = res.data
        if (data.areaName) {
          data.areaName = (data.areaName.replace(/,/g, '/').replace(/\s+/g, ''))+(data.areaId.indexOf(',') > -1 ? '': '及以上')
        }
        data.moneyList = JSON.parse(data.costMoney);
        data.stock = Math.max(0, data.stock - data.useStock)
        this.payType = data.isFree == 2 ? -2: 5
        this.device = res.data
      })
    },
    changeAgreement() {
      this.isAgreement = !this.isAgreement
      if (this.isAgreement) {
        this.agreeTipShow = false
      }
    },
    async createOrder() {
      if (!this.isAgreement) {
        this.agreeTipShow = true
        return
      }
      const params = {
        equipmentId: this.device.equipmentId,
        cashMoney: this.device.cashMoney,
        costMoney: JSON.stringify(this.currMoney),
        money: this.currMoney.price,
        payType: Math.max(this.payType, 5),
        freeType: this.payType < 0 ? Math.abs(this.payType): 0,
        orderType: 3,
      }
      console.log(params)
      if (this.submitLoading) return
      this.submitLoading = true
      const orderRes = await createLeaseOrder({
        data: encryptByDESModeCBCUtf8to64(JSON.stringify(params))
      })
      if (orderRes.code != 200) {
        this.$Message.error(orderRes.msg || '创建订单失败')
        this.submitLoading = false
        return
      }
      if (orderRes.data.status == 3) {
        this.paySuccess()
        return
      }
      const payParams = {
        ...orderRes.data,
        orderType: 3,
        orderMoney: this.totalPrice
      }
      const payRes = await leaseOrderPay({
        data: encryptByDESModeCBCUtf8to64(JSON.stringify(payParams))
      })
      if (payRes.code != 200) {
        this.$Message.error(payRes.msg || '支付失败')
        this.submitLoading = false
        return
      }
      this.payModel = {
        show: true,
        ...payParams,
        qrcode: payRes.data.imgUrl
      }
    },
    paySuccess() {
      this.show = false
      this.submitLoading = false
      this.payModel = {
        finishShow: true
      }
      this.$emit('success', this.device)
    },
    payFail() {
      this.submitLoading = false
    }
  },
  watch: {
    show(val) {
      val && this.init()
    }
  },
}
</script>

<style scoped lang="scss">
@import "detail.scss";
</style>
